package com.example.demo.Config.QuartzConfig;

import com.example.demo.Config.EssayTask.EssayTask;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * Quartz 定时任务配置类，用于配置 EssayTask 任务的执行细节。
 */
@Configuration
public class QuartzConfig {

    private static final Logger logger = LoggerFactory.getLogger(QuartzConfig.class);

    // 任务标识
    private static final String LIKE_TASK_IDENTITY = "LikeTaskQuartz";


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        // 配置其他属性，如 JobStore 等
        return new SchedulerFactoryBean();
    }

    @Bean
    public Scheduler scheduler() throws Exception {
        SchedulerFactoryBean schedulerFactoryBean = schedulerFactoryBean();
        return schedulerFactoryBean.getObject();
    }
    /**
     * 创建 JobDetail，指定任务的执行类和标识。
     *
     * @return JobDetail 对象
     */
    @Bean
    public JobDetail quartzDetail() {
        try {
            return JobBuilder.newJob(EssayTask.class)
                    .withIdentity(LIKE_TASK_IDENTITY)
                    .storeDurably()
                    .build();
        } catch (Exception e) {
            logger.error("创建 JobDetail 时发生异常", e);
            throw new RuntimeException("创建 JobDetail 失败", e);
        }
    }

    /**
     * 创建 Trigger，指定任务的触发规则。
     *
     * @return Trigger 对象
     */
    @Bean
    public Trigger quartzTrigger() {
        try {
            SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInHours(24)
                    .repeatForever();
            return TriggerBuilder.newTrigger()
                    .forJob(quartzDetail())
                    .withIdentity(LIKE_TASK_IDENTITY)
                    .withSchedule(scheduleBuilder)
                    .build();
        } catch (Exception e) {
            logger.error("创建 Trigger 时发生异常", e);
            throw new RuntimeException("创建 Trigger 失败", e);
        }
    }
}